from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from .models import *
from random import sample
from .oo import ProducePaper

# Create your views here.
def asd(request):
    #return HttpResponse('hello,world')
    a = '你好世界'
    b = list(range(10))
    context = {'aa':a,'bb':b,'cc':{1:'a',2:'b'}}
    return render(request,'paper/asd.html',context)

def index(request):#试卷选择
    #print(request.META.get("HTTP_API_AUTH"))
    print(request.method)
    #print(vars(request))
    print(request.META.get('HTTP_USER_AGENT'))
    print(request.META.get('REMOTE_ADDR'))
    
    context = {}
    return render(request,'paper/bai/index.html',context)
def home(request):

    
    context = {}
    return render(request,'paper/bai/content.html',context)
    #return HttpResponse()
    #return HttpResponseRedirect(reverse('paper:login_yunsuan'))#跳转

def stu_login(request):

    context = {}
    return render(request,'paper/bai/login.html',context)

def login_yunsuan(request):
    '''
    
    '''

    if request.method == 'POST':
    
        info = dict(request.POST)
        user_name = info['user_name'][0]
        pswd = info['pswd'][0]
        try:
            stu_info = StuId.objects.get(stu_name = user_name)
            print(stu_info.stu_pswd)
        except StuId.DoesNotExist:
            context = {'message':'你输入的用户不存在'}
            return render(request,'paper/bai/login.html',context)
        else:
            db_pswd = stu_info.stu_pswd
            if db_pswd == None:
                if stu_info.stu_id[-6:] == pswd:
                    request.session['权限'] = '学生'
                    request.session['姓名'] = user_name
                    return HttpResponseRedirect(reverse('paper:exam'))
                    #return HttpResponse(user_name+'：玩家登陆成功')
                else:
                    context = {'message':'你输入的密码不正确'}
                    return render(request,'paper/bai/login.html',context)
            elif db_pswd == pswd:
                request.session['权限'] = '学生'
                request.session['姓名'] = user_name
                return HttpResponseRedirect(reverse('paper:exam'))
                #return HttpResponse(user_name+'：玩家登陆成功')
            elif db_pswd != pswd:
                context = {'message':'你输入的密码不正确'}
                return render(request,'paper/bai/login.html',context)

    elif request.method == 'GET':
        context = {'message':'请输入账号和密码'}
        return render(request,'paper/bai/login.html',context)
        #return HttpResponseRedirect(reverse('paper:stu_login'))

    
def exam(request):
    '''\
    目的：渲染一张试卷
    目标分解：
        1、确定是否有权限，权限 = 学生
        2、获取一张试卷信息
        

    '''
    try:
        permission = request.session['权限']
        name = request.session['姓名']
    except KeyError:
        context = {}
        return render(request,'paper/bai/login.html',context)

    else:
        info_dict = {'单选题':[5,1],'填空题':[5,2],'判断题':[5,2]}
        info = ProducePaper(info_dict)
        context = info.info_dict_obj        
        paper_info_now = info.info_dict_pk
        PaperKu.objects.create(paper_name = name,paper_info = paper_info_now)
        context.update(dict(request.session))
        request.session['paper_name'] = name
        return render(request,'paper/bai/aiTest.html',context)

def exam_yunsuan(request):
    '''\
    目标：接收学生答题情况并保存到数据库
    目标分解：
        1、接收信息
        2、处理信息，方便老师阅卷

        {'单选题'：[5,1,[(12,3),...]],}
        

    '''
    if request.method == 'GET':
        context = {}
        return render(request,'paper/bai/login.html',context)
    elif request.method == 'POST':
        '''
<QueryDict: {'csrfmiddlewaretoken':
['pK37s5Gws6vU1fSeybOADAk9iXLQhgxtSHEKRo1q1XOtsGDrKe0Hi
NchaV1HN873'], '53': ['23'], '1': ['2'], '25': ['5'],
'54': ['28'], '57': ['38'], '4': ['的'], '19': ['和'],
'34': [' 主 '], '23': ['产'], '44': ['不'], '10': ['错'],
'20': ['对'], '2': ['错'], '5': ['对'], '12': ['错']}>

        '''
        paper_name = request.session['paper_name']
        
        paper_obj = PaperKu.objects.get(paper_name = paper_name)
        paper_info = eval(paper_obj.paper_info)

        info_dict = dict(request.POST)
        stu_name = request.session['姓名']
        

        for value in paper_info.values():
            value[2] = [(i,info_dict[str(i)][0]) for i in value[2]]

        StuPaperAnswerSave.objects.create(answer = paper_info,
                stu_id = StuId.objects.get(stu_name = stu_name),
                paper = paper_obj,
                                   )
        

        
        
        

        return HttpResponse('xxxxxx')


def teacher_login(request):
    context = {'teacher':'teacher'}
    return render(request,'paper/bai/login.html',context)


def teacher_login_yunsuan(request):
    if request.method == 'GET':
        return HttpResponseRedirect(reverse('paper:teacher_login'))
    if request.method == 'POST':
        info_post = dict(request.POST)
        teacher_name = info_post['user_name'][0]
        pswd = info_post['pswd'][0]

        try:
            teacher_obj = Teacher.objects.get(
                teacher_name = teacher_name)
        except Teacher.DoesNotExist:

            context = {'teacher':'teacher',
                       'message':'你输入的账号不存在'}
            return render(request,'paper/bai/login.html',context)

        else:
            if teacher_obj.pswd == pswd:
                request.session['权限'] == '老师'
                return HttpResponse('登陆成功')
            elif teacher_obj.pswd != pswd:

                context = {'teacher':'teacher',
                       'message':'你输入密码错误'}
                return render(request,'paper/bai/login.html',context)
                
        
            

        
        
        
    
    
        



















def index_yunsuan(request):#生成试卷必要运算
    info = dict(request.POST)
    paper_name = info['paper_name'][0]

    context_dict = {}
    info_dict = {}
    for question_type,question_info in info.items():
        if question_info[0] != '' and not \
           question_type.startswith('csrf') and \
           question_type !='paper_name':
                qu_type = QuestionType.objects.\
                          get(pk = question_info[0])
                question = sample(list(qu_type.question_set.all()),int(question_info[1]))
                question_id = [que.pk for que in question]
                #question_info[:].append(question)
                context_dict[qu_type.question_type] = question_info[:]
                
                context_dict[qu_type.question_type].append(question)

                info_dict[qu_type.question_type] = question_info[:]

                info_dict[qu_type.question_type].append(question_id)
                
                
                            

    context = context_dict
    
    print(context)
    print(info_dict)

    PaperKu(paper_name = paper_name,paper_info = info_dict).save()
    return render(request,'paper/index_yunsuan.html',{'context':context})
    

def dati(request):#数据渲染
    info = {'单选题':[10,1],
     '填空题':[5,2],
     '判断题':[5,1],
     '英汉互译题':[10,3]}

    context = ProducePaper(info).paper_info_obj
    
    print(context)
    #context = {}
    return render(request,'paper/paper.html',context)

def dati_tijiao_info(request):#接收考试完提交的信息，并运算
    
    context = request.POST
    print(context)
    return render(request,'paper/dati_tijiao_info.html',context)



def paper_ku_index(request):
    paper_ku = PaperKu.objects.all()

    context = {'paper_ku':paper_ku}
    return render(request,'paper/paper_ku_index.html',context)


def paper_show(request,paper_id):
    paper_info =eval(PaperKu.objects.get(pk = paper_id).paper_info)

    for key,value in paper_info.items():
        value[3]= [Question.objects.get(pk = pknow) \
                   for pknow in value[3]]
    

    context = {'context':paper_info}
    return render(request,'paper/index_yunsuan.html',context)












def info_jiekou(request):


	context = {}
	return render(request,'paper/info_jiekou.html',context)
	#return HttpResponse('提交成功')
	
def info_jiekou_yunsuan(request):

	'''<QueryDict: {'csrfmiddlewaretoken': 
	['Xu9GD5AqMDSwOub0pw7Ncjf3DfPB5yjcbcw2Dg
	o9MKAKc196rhH7lZfnWFTQ7R4z'], 
	'question_type': ['1'], 
	'question': ['所有M是P，所有S是M，
	因此不对的结论是（  ）'], 
	'choice': ['所有S是P', '所有S是Px', 
	'所有M是S', ''], 'answer': ['所有M是S']}>
	'''

	info_dict = dict(request.POST)
	type_id = info_dict['question_type'][0]
	if info_dict['question'][0] =='' or info_dict['answer'][0] == '':
	
		return HttpResponse('请检查是否输入问题和答案')
		
	
	question_type = QuestionType.objects.get(pk = type_id)
	
	question = question_type.question_set.create(
				question_text = info_dict['question'][0])
	
	question.answer_set.create(answer_text = info_dict['answer'][0])
	
	for choice in info_dict['choice']:
		if choice != '':
			question.choice_set.create(
				choice_text = choice)
	
	
	

	
	return HttpResponse('添加成功')
	

def test(request):
    body = '''\
<body id="generic" class="">

    <div role="banner" id="top">
  <div class="container">
    <a class="logo" href="https://www.djangoproject.com/">Django</a>
    <p class="meta">The web framework for perfectionists with deadlines.</p>
    <div role="navigation">
      <ul>
        <li>
          <a href="https://www.djangoproject.com/start/overview/">Overview</a>
        </li>
        <li>
          <a href="https://www.djangoproject.com/download/">Download</a>
        </li>
        <li class="active">
          <a href="https://docs.djangoproject.com/">Documentation</a>
        </li>
        <li>
          <a href="https://www.djangoproject.com/weblog/">News</a>
        </li>
        <li>
          <a href="https://www.djangoproject.com/community/">Community</a>
        </li>
        <li>
          <a href="https://code.djangoproject.com/">Code</a>
        </li>
        <li>
          <a href="https://www.djangoproject.com/foundation/">About</a>
        </li>
        <li>
          <a href="https://www.djangoproject.com/fundraising/">&#9829; Donate</a>
        </li>
      </ul>
    </div>
  </div>
</div>
</body>'''
    context = {'bo':body,'list':list(range(10)),'aa':'AA','bb':'BB'}
    return render(request,'paper/test.html',context)






















